//
//  SLPermissionSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/25.
//

#import "SLLockDetailVC.h"
#import "SLLockDetailView.h"
#import "SLUnlockAlertView.h"
#import "SLLockLogVC.h"
#import "SLUpdateFirmVC.h"
#import "SLAccessManagerVC.h"
#import "SLDeviceSettingVC.h"

@interface SLLockDetailVC (){
    
}
@property (nonatomic, strong)NSDictionary *updateInfo;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLLockDetailView *detailView;
@property (nonatomic, assign)NSInteger sysncCount;

@end

@implementation SLLockDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    
    [ZCTool connectDeviceWith:_model toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        if (isSuccess) {
            [self getDeviceData];
            [self checkUpdate];
        }
    }];
}

//获取设备信息
-(void)getDeviceData{
    kWeakSelf(self);
    //电池电量数据
    [[SLBluetoothManager sharedManager] getDeviceStatusInfo:^(id data) {
        [weakself refreshWithStatusInfo:data];
        [weakself sysncBatteryInfo:data];
    }];
}

-(void)refreshWithStatusInfo:(NSDictionary *)data{
    self.detailView.batteryLbl.text = [NSString stringWithFormat:@"%@%%",data[@"batteryLevel"]];
    self.detailView.temptureLbl.text = [ZCTool temperatureWith:kSTRING(data[@"temperature"])];
}

-(void)sysncBatteryInfo:(NSDictionary *)data{
    NSDictionary *params = @{@"deviceElectricQty":data[@"batteryLevel"]};
    [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            return;
        }
        //修改成功
        kNotifyRefreshDevcieList;
    }];
}

-(void)backBtnClicked{
    [super backBtnClicked];
//    [[SLBluetoothManager sharedManager] disConnectPeripheral];
}

-(void)sysncDeviceData{
    [_tableView beginRefreshing];
    //同步开锁日志和钥匙数据
    kWeakSelf(self);
    _sysncCount = kCurClickDevice.isGuest ? 1 : 3;
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        if (isSuccess) {
            if (!kCurClickDevice.isGuest) {
                [ZCTool batchSyncDeviceKeyDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
                    [weakself hanldeSyncFinish];
                }];
                
                [ZCTool batchSyncDeviceOpenLogDatas:^(BOOL isSuccess, NSString * _Nonnull message) {
                    [weakself hanldeSyncFinish];
                }];
            }
            
            [[SLBluetoothManager sharedManager] getDeviceStatusInfo:^(id data) {
                [weakself refreshWithStatusInfo:data];
                NSDictionary *params = @{@"deviceElectricQty":data[@"batteryLevel"]};
                [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
                    [weakself hanldeSyncFinish];
                }];
            }];
        }else{
            [self->_tableView endRefresh];
        }
    }];
}

-(void)hanldeSyncFinish{
    _sysncCount --;
    if (_sysncCount == 0){
        NSString *time = [[NSDate date] timestamp];
        [ZKHttpManager sysncDeviceDataWith:@{@"syncTime":time} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [self->_tableView endRefresh];
            MJRefreshNormalHeader *normalHeader = (MJRefreshNormalHeader *)self->_tableView.mj_header;
            normalHeader.lastUpdatedTimeLabel.text = [ZCTool updateTimeWith:time];
            kNotifyRefreshDevcieList;
        }];
    }
}

//检查升级
-(void)checkUpdate{
    
    //先获取硬件的固件版本号
    [[SLBluetoothManager sharedManager] getDeviceBaseInfo:^(id data) {
        //校验是否有新的固件版本
        [ZCTool checkUpdateInfo:data[@"version"] finish:^(BOOL needUpdate, id  _Nonnull updateInfo) {
            if (!needUpdate) return;
            [self showUpdateAlertView:updateInfo];
        }];
    }];
}

-(void)setUpSubViews{
    self.title = _model.deviceName;
    [self.view addSubview:self.tableView];
    _detailView = [SLLockDetailView viewFromXIB];
    _detailView.frame = self.tableView.bounds;
    _detailView.model = _model;
    kWeakSelf(self);
    [_detailView setBtnBlock:^(NSString *title) {
        [weakself handleSetView:title];
    }];
    _tableView.tableHeaderView = _detailView;
}

-(void)showUpdateAlertView:(NSDictionary *)updateInfo{
    if ([ZCTool getCurrentUIVC] != self) return;
    if (kCurClickDevice.isGuest) return;
    NSString *desc = kLocalString(@"Update available for <1> New ver <2>");
    desc = [desc stringByReplacingOccurrencesOfString:@"<1>" withString:kCurDevice.productName];
    desc = [desc stringByReplacingOccurrencesOfString:@"<2>" withString:[NSString stringWithFormat:@"%@",updateInfo[@"serverVersion"]]];
    [SLTipAlertView showWith:kLocalString(@"New firmware update available") content1:desc content2:@"" doneBtn:kLocalString(@"Go to update") cancelBtn:kLocalString(@"Remind me later") action:^(NSInteger index) {
        if (index == 1) {
            SLUpdateFirmVC *vc = [[SLUpdateFirmVC alloc] init];
            vc.updateInfo = updateInfo;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}

-(void)handleSetView:(NSString *)title{
    if ([title isEqualToString:kLocalString(@"Access management")]) {
        SLAccessManagerVC *vc = [[SLAccessManagerVC alloc] init];
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:kLocalString(@"Activity logs")]){
        SLLockLogVC *vc = [[SLLockLogVC alloc] init];
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:kLocalString(@"Lock settings")]){
        SLDeviceSettingVC *vc = [[SLDeviceSettingVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:kLocalString(@"Sync")]){//同步
        [self sysncDeviceData];
    }else if ([title isEqualToString:kLocalString(@"Unlock")]){
        
        [ZCTool connectDeviceWith:_model toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
            if (!isSuccess) {
                kShowToast(@"Connect faild");
                return;
            }
            [self showUnAlert:^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [self->_detailView playAnimation];
                    [AnimationLoader playAnimationAndStopWithAnimationView:self->_detailView.animation for:1];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [ZCTool sendOpenLockSegment:^(BOOL isSuccess ,NSString *message) {
                            kShowToast(message);
                        }];
                    });
                });
            }];
        }];
    }
    else if ([title isEqualToString:kLocalString(@"Delete this access")]){
        [self deleteShareAccess];
    }
}

-(void)showUnAlert:(void(^)(void))finish{
    SLUnlockAlertView *alert = [SLUnlockAlertView viewFromXIB];
    if (kCurClickDevice.bridgeDeviceNo.length > 0) {
        alert.style = 2;  // 网关锁
    } else {
        alert.style = 1;  // 蓝牙锁
    }
    alert.model = kCurClickDevice;
    alert.tag = 110;
    [kAppWindow addSubview:alert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert removeFromSuperview];
        if (finish) finish();
    });
}

//删除分享的钥匙
-(void)deleteShareAccess{
    
    [SLTipAlertView showWith:kLocalString(@"Make sure you want to delete this access?") content1:kLocalString(@"You can reclaim this access again by visiting the access link you received.") content2:@"" doneBtn:kLocalString(@"Delete") cancelBtn:kLocalString(@"Cancel") action:^(NSInteger index) {
        if (index == 0) {
            return;
        }
        //先硬件端删除
        [ZCTool showLoadingOnKeyWindowWith:kLocalString(@"Deleting...")];
        NSString *url = [NSString stringWithFormat:@"/msl_lock_key/delete/%@",self->_model.keyId];
        [ZKHttpManager deleteWithPath:url params:nil finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            
            kShowToast(@"Delete success!");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
                kNotifyRefreshDevcieList;
            });
        }];
    }];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KClearColor;
        kWeakSelf(self);
        [_tableView addHeadRefreshWithRefreshingBlock:^{
            [weakself sysncDeviceData];
        }];
    }
    return _tableView;
}


@end
